import { RouteObject } from 'react-router-dom';
import { SysMenu } from '../api/menu';
import { authApi } from '../api/auth';

/**
 * 路由管理器
 * 提供动态路由的创建、缓存和管理功能
 */
export class RouteManager {
  private static instance: RouteManager;
  private menuCache: SysMenu[] | null = null;
  private cacheExpiry: number = 0;
  private readonly CACHE_DURATION = 5 * 60 * 1000; // 5分钟缓存

  private constructor() {}

  public static getInstance(): RouteManager {
    if (!RouteManager.instance) {
      RouteManager.instance = new RouteManager();
    }
    return RouteManager.instance;
  }

  /**
   * 获取用户菜单（带缓存）
   */
  public async getUserMenus(forceRefresh = false): Promise<SysMenu[]> {
    const now = Date.now();
    
    // 检查缓存是否有效
    if (!forceRefresh && this.menuCache && now < this.cacheExpiry) {
      return this.menuCache;
    }

    try {
      const menus = await authApi.getUserMenus() as SysMenu[];
      this.menuCache = menus;
      this.cacheExpiry = now + this.CACHE_DURATION;
      return menus;
    } catch (error) {
      console.error('获取用户菜单失败:', error);
      // 如果有缓存，返回缓存数据
      if (this.menuCache) {
        console.warn('使用缓存的菜单数据');
        return this.menuCache;
      }
      throw error;
    }
  }

  /**
   * 清除菜单缓存
   */
  public clearCache(): void {
    this.menuCache = null;
    this.cacheExpiry = 0;
  }

  /**
   * 根据菜单路径获取组件名称
   */
  public getComponentName(menuPath: string): string {
    if (!menuPath) return '';
    
    // 移除开头的斜杠并转换为驼峰命名
    const path = menuPath.replace(/^\//, '');
    
    // 特殊路径映射
    const pathMapping: Record<string, string> = {
      'dashboard': 'Dashboard',
      'system/user': 'UserManagement',
      'system/role': 'RoleManagement', 
      'system/permission': 'PermissionManagement',
      'system/menu': 'MenuManagement',
      'system/permission-assignment': 'PermissionAssignment',
    };
    
    return pathMapping[path] || this.generateComponentName(path);
  }

  /**
   * 自动生成组件名称
   */
  private generateComponentName(path: string): string {
    return path
      .split('/')
      .map(segment => 
        segment
          .split('-')
          .map(word => word.charAt(0).toUpperCase() + word.slice(1))
          .join('')
      )
      .join('') + 'Management';
  }

  /**
   * 验证菜单路径是否有效
   */
  public isValidMenuPath(menuPath: string): boolean {
    if (!menuPath) return false;
    
    // 检查路径格式
    const pathRegex = /^\/?[a-zA-Z0-9\-\/]+$/;
    return pathRegex.test(menuPath);
  }

  /**
   * 获取菜单层级结构
   */
  public getMenuHierarchy(menus: SysMenu[]): Map<number, SysMenu[]> {
    const hierarchy = new Map<number, SysMenu[]>();
    
    const processMenus = (menuList: SysMenu[], level: number) => {
      if (!hierarchy.has(level)) {
        hierarchy.set(level, []);
      }
      
      menuList.forEach(menu => {
        hierarchy.get(level)!.push(menu);
        
        if (menu.children && menu.children.length > 0) {
          processMenus(menu.children, level + 1);
        }
      });
    };
    
    processMenus(menus, 0);
    return hierarchy;
  }

  /**
   * 查找菜单项
   */
  public findMenu(menus: SysMenu[], predicate: (menu: SysMenu) => boolean): SysMenu | null {
    for (const menu of menus) {
      if (predicate(menu)) {
        return menu;
      }
      
      if (menu.children && menu.children.length > 0) {
        const found = this.findMenu(menu.children, predicate);
        if (found) {
          return found;
        }
      }
    }
    
    return null;
  }

  /**
   * 获取菜单路径数组
   */
  public getMenuPaths(menus: SysMenu[]): string[] {
    const paths: string[] = [];
    
    const extractPaths = (menuList: SysMenu[]) => {
      menuList.forEach(menu => {
        if (menu.menuPath && menu.menuType === 2) { // 只收集菜单类型的路径
          paths.push(menu.menuPath);
        }
        
        if (menu.children && menu.children.length > 0) {
          extractPaths(menu.children);
        }
      });
    };
    
    extractPaths(menus);
    return paths;
  }

  /**
   * 验证路由配置
   */
  public validateRouteConfig(routes: RouteObject[]): boolean {
    try {
      // 检查路由配置的基本结构
      for (const route of routes) {
        if (!route.path) {
          console.warn('发现无效路由配置: 缺少path属性');
          return false;
        }
        
        if (!route.element) {
          console.warn(`发现无效路由配置: 路径 ${route.path} 缺少element属性`);
          return false;
        }
      }
      
      return true;
    } catch (error) {
      console.error('路由配置验证失败:', error);
      return false;
    }
  }

  /**
   * 获取路由统计信息
   */
  public getRouteStats(menus: SysMenu[]): {
    totalMenus: number;
    routeMenus: number;
    directoryMenus: number;
    buttonMenus: number;
    maxDepth: number;
  } {
    let totalMenus = 0;
    let routeMenus = 0;
    let directoryMenus = 0;
    let buttonMenus = 0;
    let maxDepth = 0;
    
    const analyzeMenus = (menuList: SysMenu[], depth: number) => {
      maxDepth = Math.max(maxDepth, depth);
      
      menuList.forEach(menu => {
        totalMenus++;
        
        switch (menu.menuType) {
          case 1:
            directoryMenus++;
            break;
          case 2:
            routeMenus++;
            break;
          case 3:
            buttonMenus++;
            break;
        }
        
        if (menu.children && menu.children.length > 0) {
          analyzeMenus(menu.children, depth + 1);
        }
      });
    };
    
    analyzeMenus(menus, 0);
    
    return {
      totalMenus,
      routeMenus,
      directoryMenus,
      buttonMenus,
      maxDepth
    };
  }
}

// 导出单例实例
export const routeManager = RouteManager.getInstance();